#include "SerialPortFactory.h"



SerialPortFactory::SerialPortFactory()
{
}


SerialPortFactory::~SerialPortFactory()
{
}

void SerialPortFactory::init() {
	if (ios == NULL) {
		ios.reset(new io_service());
	}

	if (ios_worker == NULL) {
		ios_worker.reset(new worker(*ios.get()));
	}
}

void SerialPortFactory::close(){
	ios_worker.reset();
}

void SerialPortFactory::run() {
	//std::cout << 3;
	ios->run();
}

std::size_t SerialPortFactory::run_one(boost::system::error_code & ec){
	return ios->run_one(ec);
}

void SerialPortFactory::insert_serial_info(const __int64 fd, SerialPortInfoPtr serialPortInfo) {
	boost::mutex::scoped_lock slock(lock);
	map.insert(std::make_pair(fd, serialPortInfo));
}

void SerialPortFactory::remove_serial_info(const __int64 fd) {
	boost::mutex::scoped_lock slock(lock);
	map.erase(fd);
}

SerialPortInfoPtr SerialPortFactory::get_serial_info(const __int64 fd) {
	boost::mutex::scoped_lock slock(lock);
	boost::unordered_map<const __int64, SerialPortInfoPtr>::iterator it = map.find(fd);

	if (it == map.end()) {
		return SerialPortInfoPtr();
	}
	else {
		return it->second;
	}
}

void SerialPortFactory::uninit() {
	boost::mutex::scoped_lock slock(lock);
	boost::unordered_map<const __int64, SerialPortInfoPtr>::iterator it = map.begin();
	
	while (it != map.end()) {
		SerialPortInfoPtr p = (*it).second;
		p->get_serial_port_ptr()->cancel();
		p->get_serial_port_ptr()->close();

		it++;
	}

	map.clear();
	ios_worker.reset();
}
